"""
检测服务模块
封装YOLO检测引擎的功能，提供统一的检测接口
"""
import logging
import numpy as np
import cv2
from detection_engine import DetectionEngine

logger = logging.getLogger(__name__)


class DetectionService:
    """检测服务类"""
    
    def __init__(self):
        """初始化检测服务"""
        logger.info("初始化检测服务...")
        # 初始化检测引擎
        self.detection_engine = DetectionEngine()
        logger.info("检测服务初始化完成")
    
    def detect_objects(self, image: np.ndarray, detection_mode: str = 'traffic') -> list:
        """
        检测图像中的目标
        
        Args:
            image: 输入图像（BGR格式）
            detection_mode: 检测模式 ('traffic', 'helmet', 'face')
            
        Returns:
            list: 检测结果列表
        """
        try:
            logger.info(f"开始检测，模式: {detection_mode}")
            
            # 设置检测模式
            self.detection_engine.set_detection_mode(detection_mode)
            
            # 执行检测
            results = self.detection_engine.detect(image)
            
            # 过滤结果，只返回需要的字段
            filtered_results = []
            for result in results:
                filtered_result = {
                    'id': result.get('id'),
                    'class': result.get('class'),
                    'confidence': result.get('confidence'),
                    'bbox': result.get('bbox_xyxy', result.get('bbox'))
                }
                filtered_results.append(filtered_result)
            
            logger.info(f"检测完成，共检测到 {len(filtered_results)} 个目标")
            return filtered_results
            
        except Exception as e:
            logger.error(f"检测过程中发生错误: {str(e)}")
            # 返回空列表而不是抛出异常，保证服务可用性
            return []
    
    def visualize_detections(self, image: np.ndarray, detections: list) -> np.ndarray:
        """
        可视化检测结果
        
        Args:
            image: 原始图像
            detections: 检测结果列表
            
        Returns:
            np.ndarray: 可视化后的图像
        """
        try:
            # 使用检测引擎的可视化功能
            return self.detection_engine.visualize_results(image, detections)
        except Exception as e:
            logger.error(f"可视化过程中发生错误: {str(e)}")
            # 如果可视化失败，返回原始图像
            return image.copy()
    
    def get_model_health(self) -> dict:
        """
        获取模型健康状态
        
        Returns:
            dict: 模型健康状态信息
        """
        try:
            return self.detection_engine.check_model_health()
        except Exception as e:
            logger.error(f"获取模型健康状态失败: {str(e)}")
            return {
                'status': 'error',
                'message': str(e)
            }
    
    def update_thresholds(self, confidence_threshold: float = None, iou_threshold: float = None):
        """
        更新检测阈值
        
        Args:
            confidence_threshold: 置信度阈值
            iou_threshold: IOU阈值
        """
        try:
            if confidence_threshold is not None:
                self.detection_engine.set_confidence_threshold(confidence_threshold)
                logger.info(f"更新置信度阈值: {confidence_threshold}")
            
            if iou_threshold is not None:
                self.detection_engine.set_iou_threshold(iou_threshold)
                logger.info(f"更新IOU阈值: {iou_threshold}")
        except Exception as e:
            logger.error(f"更新阈值失败: {str(e)}")
    
    def batch_detect(self, images: list, detection_mode: str = 'traffic') -> list:
        """
        批量检测图像
        
        Args:
            images: 图像列表
            detection_mode: 检测模式
            
        Returns:
            list: 检测结果列表
        """
        results = []
        for i, image in enumerate(images):
            try:
                logger.info(f"处理批量图像 {i+1}/{len(images)}")
                detection_result = self.detect_objects(image, detection_mode)
                results.append({
                    'index': i,
                    'detections': detection_result
                })
            except Exception as e:
                logger.error(f"处理批量图像 {i+1} 失败: {str(e)}")
                results.append({
                    'index': i,
                    'detections': [],
                    'error': str(e)
                })
        
        return results